const express = require("express");
const cors = require("cors");
const app = express();
const joi = require("joi");
const config = require("./config");
const { expressjwt } = require("express-jwt");
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use('/uploads', express.static('./uploads'))

app.use((req, res, next) => {
  // status 的默认值为 1，表示失败的情况
  res.sd = (err, status = 1) => {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});

// 使用 unless 方法指定哪些接口不需要进行 Token 的身份认证
app.use(expressjwt({ secret: config.jwtSecretKey, algorithms: ["HS256"] }).unless({ path: [/^\/api\//] }));

app.use("/api", require("./router/user.js"));
app.use("/my", require("./router/userinfo.js"));
app.use('/my/article', require('./router/artcate.js'))
app.use('/my/article', require('./router/article.js'))

// 错误中间件
app.use((err, req, res, next) => {
  // 数据验证失败
  if (err instanceof joi.ValidationError) return res.sd(err);
  if (err.name === "UnauthorizedError") return res.sd("身份认证失败！");
  // 未知错误
  res.sd(err);
});

app.listen(3000, () => console.log("api server running at http://127.0.0.1:3000"));
